﻿layui.use(['form', 'tree', 'util', 'layer'], function () {
    var $ = layui.jquery;
    var tree = layui.tree
        , layer = layui.layer
        , util = layui.util;
    var form = layui.form;
    var test = [];

    if (getQueryStringByCN("Type") === "1" || getQueryStringByCN("Type") === "3") {
        if (getQueryStringByCN("Type") === "1") {
            $('#RoleName').attr("disabled", true);
        }
        $('#RoleType').attr("disabled", true);
        $('#admin3').remove();
    }
    if (getQueryStringByCN("Type") === "4") {
        $('#admin').remove();
        $('#admin2').remove();
    }

    //监听提交
    form.on('submit(formDemo)', function (data) {
        test.length = 0;
        let PostData = [];
        let dataTest = {};
        dataTest.RoleName = data.field.RoleName;
        dataTest.Note = data.field.Note;
        dataTest.RoleType = data.field.RoleType;
        dataTest.ControlType = data.field.ControlType;
        PostData.push(dataTest);
        var checkData = tree.getChecked('MenuId');
        for (var i = 0; i < checkData.length; i++) {
            test.push(checkData[i].id);
            if (checkData[i].children !== undefined && checkData[i].children.length !== 0) {
                for (var j = 0; j < checkData[i].children.length; j++) {
                    test.push(checkData[i].children[j].id);
                }
            }
        }

        if (getQueryStringByCN("Type") === "3") {
            //if (dataTest.RoleName === "超级管理员" || dataTest.RoleName === "普通教工") {
            //    layui.layer.alert("已有超级管理员以及普通教工的角色，不能再添加");
            //    return false;
            //}
            var data = {
                MenuList: test,
                roleList: PostData,
            }
            console.log(JSON.stringify(data));

            $.postJSON('api/Role/Insert', data, (data) => {
                if (data.code === "200") {
                    swal({
                        icon: 'success',
                        title: '添加成功！',
                    }).then(function () {
                        parent.location = parent.location;
                    });
                } else if (data.code === "500") {
                    layer.alert("添加失败");
                }
            })
        } else {
            //$.ajax({
            //    url: "api/Role/Update",
            //    type: 'post',
            //    data: {
            //        MenuList: JSON.stringify(test),
            //        PostData: JSON.stringify(PostData),
            //        Id: getQueryStringByCN("Card"),
            //    },
            //    dataType: 'json',
            //    success: function (json) {
            //        if (json.msg === "success") {
            //            PostData = [];
            //            swal({
            //                icon: 'success',
            //                title: '修改成功',
            //            }).then(function () {
            //                parent.location = parent.location;
            //            });
            //        } else {
            //            handleApiError(json)
            //        }
            //    }
            //});
            const data = {
                MenuList: test,
                roleList: PostData,
                Id: getQueryStringByCN("Card"),
            }
            $.postJSON('api/Role/UpdateRole', data, (data) => {
                if (data.code == 200) {
                    PostData = [];
                    swal({
                        icon: 'success',
                        title: '修改成功',
                    }).then(function () {
                        parent.location = parent.location;
                    });
                } else {
                    layer.alert(data.msg);
                }
            })
        }
        return false;
    });

    //监听提交
    form.on('submit(addNode)', function (data) {
        data.field.MenuId = "0"
        $.postJSON('api/Menu/Insert', data.field, (data) => {
            if (data.code === "200") {
                layer.msg('添加成功！', { icon: 1 });
                setTimeout(function () {
                    window.location.reload();
                }, 500);
            } else if (data.msg === "500") {
                layer.alert("添加失败");
            }
        })
        return false;
    });
    //监听提交
    form.on('submit(addFatherNode)', function (data) {
        data.field.FatherId = "0"
        data.field.MenuId = "0"
        $.postJSON('api/Menu/Insert', data.field, (data) => {
            if (data.code == "200") {
                layer.msg('添加成功！', { icon: 1 });
                setTimeout(function () {
                    window.location.reload();
                }, 500);
            } else if (data.code == "500") {
                layer.alert(data.msg);
            }
        })
        return false;
    });

    //监听修改
    form.on('submit(updateNode)', function (data) {
        $.postJSON('api/Menu/Update', data.field, (data) => {
            if (data.code === "200") {
                layer.msg('修改成功！', { icon: 1 });
                setTimeout(function () {
                    window.location.reload();
                }, 500);
                // location=location
            } else {
                layer.alert("修改失败");
            }
        })
        return false;
    });

    //监听按钮
    form.on('submit(addFatherMenu)', function (data) {
        layer.open({
            type: 1,
            title: "新增",
            area: ['500px', '500px'],
            content: $("#add-FatherNode"),
        });
        return false;
    });
    getAllMenu();
    function getAllMenu() {
        $.getData('api/Menu/FindMenu', (data) => {
            let dd = toTree(data.data, 0);
            showTree(dd);
        })
    }
    function toTree(data, id) {
        let result = [], temp;
        for (var i = 0; i < data.length; i++) {
            if (data[i].fatherId == id) {
                let obj = data[i];
                temp = toTree(data, data[i].menuId);
                if (temp.length > 0) {
                    obj.children = temp;
                }
                obj.spread = false;
                obj.title = obj.menuName;
                obj.id = obj.menuId;
                result.push(obj);
            }
        }
        return result;
    }

    function showTree(dd) {
        debugger;
        if (getQueryStringByCN("Card") !== undefined && getQueryStringByCN("Card") !== null) {
            let CardData = getQueryStringByCN("Card");
            getRoleInfo(CardData, dd);
        } else {
            if (getQueryStringByCN("Type") === "4") {
                var index0pen
                //开启复选框
                tree.render({
                    elem: '#test7'
                    , data: dd
                    , showCheckbox: true
                    , edit: ['add', 'update', 'del'] //操作节点的图标
                    , id: 'MenuId' //定义索引
                    , customOperate: true
                    , operate: function (obj) {
                        var type = obj.type; //得到操作类型：add、edit、del
                        var data = obj.data; //得到当前节点的数据
                        var elem = obj.elem; //得到当前节点元素

                        //Ajax 操作
                        var id = data.id; //得到节点索引
                        if (type === 'add') { //增加节点
                            $("#add-form input[name='FatherId']").val(id);
                            //$("#add-form input[name='MenuId']").val('');
                            index0pen = layer.open({
                                type: 1,
                                title: "新增",
                                area: ['500px', '500px'],
                                content: $("#add-node"),
                            });
                        } else if (type === 'update') { //修改节点
                            $("#update-form input[name='FatherId']").val(data.fatherId);
                            $("#update-form input[name='Href']").val(data.href);
                            $("#update-form input[name='MenuId']").val(data.menuId);
                            $("#update-form input[name='MenuName']").val(data.menuName);
                            $("#update-form input[name='Sort']").val(data.sort);
                            index0pen = layer.open({
                                type: 1,
                                title: "修改",
                                area: ['500px', '500px'],
                                content: $("#update-node")
                            });
                        } else if (type === 'del') { //删除节点
                            $.postJSON('api/Menu/Delete', data, (data) => {
                                if (data.code == "200") {
                                    //关闭
                                    layer.close(index0pen);
                                    layer.msg('删除成功！', { icon: 1 });
                                    setTimeout(function () {
                                        window.location.reload();
                                    }, 500);
                                } else {
                                    layer.msg("删除失败", { icon: 2 });
                                }
                            })
                        }
                    }
                });
            } else {
                //开启复选框
                tree.render({
                    elem: '#test7'
                    , data: dd
                    , showCheckbox: true
                    , id: 'MenuId' //定义索引
                });
            }
        }

    }

    function getRoleInfo(id, dd) {
        $.getData('api/Role/GetRoleInfo', { Id: id }, (res) => {
            //开启复选框
            tree.render({
                elem: '#test7'
                , data: dd
                , showCheckbox: true
                , id: 'MenuId' //定义索引
            });
            form.val("formTest", { //formTest 即 class="layui-form" 所在元素属性 lay-filter="" 对应的值
                "RoleName": res.data.roleName, // "name": "value"
                "Note": res.data.note, // "name": "value"，
                "ControlType": res.data.controlType,
                "RoleType": res.data.roleType
            });
            form.render();
            tree.setChecked('MenuId', res.data.rolePower.split(',')); //批量勾选 id 为 2、3 的节点
        })
    }

});